import {createRouter, createWebHistory} from 'vue-router'
import {useUserStore} from '@/stores/user'

const routes = [{
    path: '/login',
    name: 'Login',
    component: () => import('@/views/Login.vue'),
    meta: {title: '登录', requiresAuth: false}
}, {
    path: '/', redirect: '/login', meta: {requiresAuth: false}
}, {
    path: '/front/home',
    name: 'FrontHome',
    component: () => import('@/views/front/HomePage.vue'),
    meta: {title: '志愿服务首页', requiresAuth: false}
}, {
    path: '/activity/:id',
    name: 'FrontActivityDetail',
    component: () => import('@/views/front/ActivityDetail.vue'),
    meta: {title: '活动详情', requiresAuth: false}
},
    {
        path: '/admin',
        name: 'Layout',
        component: () => import('@/layout/index.vue'),
        redirect: '/admin/dashboard',
        meta: {requiresAuth: true},
        children: [{
            path: 'dashboard',
            name: 'AdminDashboard',
            component: () => import('@/views/admin/Dashboard.vue'),
            meta: {title: '管理后台', icon: 'HomeFilled'}
        }, {
            path: 'activity',
            name: 'Activity',
            component: () => import('@/views/admin/ActivityManager.vue'),
            meta: {title: '活动管理', icon: 'Calendar'}
        }, {
            path: 'menu',
            name: 'Menu',
            component: () => import('@/views/admin/MenuManage.vue'),
            meta: {title: '菜单管理', icon: 'Menu'}
        }, {
            path: 'role',
            name: 'Role',
            component: () => import('@/views/admin/RoleManage.vue'),
            meta: {title: '角色管理', icon: 'User'}
        }, {
            path: 'user',
            name: 'User',
            component: () => import('@/views/admin/UserManage.vue'),
            meta: {title: '用户管理', icon: 'User'}
        },


            {
                path: 'notice',
                name: 'Notice',
                component: () => import('@/views/admin/NoticeManage.vue'),
                meta: {title: '系统公告', icon: 'User'}
            },

        ]
    }, {
        path: '/activity-detail/:id',
        name: 'ActivityDetail',
        component: () => import('@/views/front/ActivityDetail.vue'),
        meta: {title: '活动详情', requireAuth: false}
    }, {
        path: '/registrations',
        name: 'UserRegistrations',
        component: () => import('@/views/front/UserRegistrations.vue'),
        meta: {title: '我的报名记录', requireAuth: true}
    }, {
        path: '/profile',
        name: 'UserProfile',
        component: () => import('@/views/front/UserProfile.vue'),
        meta: {title: '个人中心', requireAuth: true}
    }, {
        path: '/delivery',
        component: () => import('@/layout/index.vue'),
        redirect: '/delivery/list',
        name: 'Delivery',
        meta: {title: '发货管理', icon: 'el-icon-truck'},
        children: [
            {
                path: 'list',
                name: 'DeliveryOrderList',
                component: () => import('@/views/delivery/OrderList.vue'),
                meta: {title: '发货订单列表', icon: 'el-icon-s-order'}
            },
            {
                path: 'create',
                name: 'CreateDeliveryOrder',
                component: () => import('@/views/delivery/OrderForm.vue'),
                meta: {title: '新增发货订单', icon: 'el-icon-plus'},
                hidden: true
            },
            {
                path: 'edit/:id',
                name: 'EditDeliveryOrder',
                component: () => import('@/views/delivery/OrderForm.vue'),
                meta: {title: '编辑发货订单', noCache: true},
                hidden: true
            },
            {
                path: 'detail/:id',
                name: 'DeliveryOrderDetail',
                component: () => import('@/views/delivery/OrderDetail.vue'),
                meta: {title: '发货订单详情', noCache: true},
                hidden: true
            },
            {
                path: 'admin/list',
                name: 'AdminDeliveryOrderList',
                component: () => import('@/views/delivery/AdminOrderList.vue'),
                meta: {title: '订单审核', icon: 'el-icon-s-check', roles: ['admin']}
            },
            {
                path: 'admin/edit/:id',
                name: 'AdminEditDeliveryOrder',
                component: () => import('@/views/delivery/OrderForm.vue'),
                meta: {title: '管理员编辑订单', noCache: true, roles: ['admin']},
                hidden: true
            },
            {
                path: 'admin/detail/:id',
                name: 'AdminDeliveryOrderDetail',
                component: () => import('@/views/delivery/OrderDetail.vue'),
                meta: {title: '管理员订单详情', noCache: true, roles: ['admin']},
                hidden: true
            }
        ]
    }, {
        path: '/:pathMatch(.*)*',
        name: 'NotFound',
        component: () => import('@/views/404.vue'),
        meta: {title: '页面不存在', requiresAuth: false}
    }]

const router = createRouter({
    history: createWebHistory(), routes
})

router.beforeEach(async (to, from, next) => {
    // 设置页面标题
    document.title = to.meta.title ? `${to.meta.title} - 发货系统系统` : '发货系统系统'

    // 获取用户store
    const userStore = useUserStore()
    const token = userStore.token

    // 如果有token但没有用户信息，尝试获取用户信息
    if (token && !userStore.name) {
        try {
            await userStore.getInfo()
        } catch (error) {
            // 如果获取用户信息失败，清除token并重定向到登录页
            userStore.resetState()
            next({name: 'Login', query: {redirect: to.fullPath}})
            return
        }
    }

    // 如果页面需要登录但用户未登录，重定向到登录页
    if (to.meta.requiresAuth !== false && !token) {
        next({name: 'Login', query: {redirect: to.fullPath}})
        return
    }

    // 如果页面需要管理员权限但用户不是管理员，重定向到首页
    if (to.meta.requiresAdmin && !userStore.isAdmin) {
        next({name: 'FrontHome'})
        return
    }

    // 如果是登录页面但用户已登录，重定向到首页
    if (to.name === 'Login' && token) {
        next({name: 'FrontHome'})
        return
    }

    next()
})

export default router
